package com.gnerv.battle.boot.framework.core.advice.api;

import com.gnerv.battle.boot.framework.core.annotation.api.ApiRequestDecrypt;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
 * 请求解密类
 *
 * @author hermes-di
 * @since 1.0.0.RELEASE
 */
@Slf4j
@RestControllerAdvice
public class ApiDecryptRequestBodyAdvice implements RequestBodyAdvice {

    @Resource
    private ApiCryptoService apiCryptoService;

    @Override
    public boolean supports(@Nonnull MethodParameter methodParameter, @Nonnull Type targetType, @Nonnull Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(ApiRequestDecrypt.class);
    }

    @Override
    public @Nonnull HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, @Nonnull MethodParameter methodParameter, @Nonnull Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        if (inputMessage.getBody().available() <= 0) {
            return inputMessage;
        }
        String decrypt = apiCryptoService.decrypt(inputMessage, methodParameter, targetType, converterType);
        byte[] requestDataByte = decrypt.getBytes(StandardCharsets.UTF_8);
        // 使用解密后的数据，构造新的读取流
        InputStream rawInputStream = new ByteArrayInputStream(requestDataByte);
        return new HttpInputMessage() {
            @Override
            public @Nonnull HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }

            @Override
            public @Nonnull InputStream getBody() {
                return rawInputStream;
            }
        };
    }

    @Override
    public @Nonnull Object afterBodyRead(@Nonnull Object body, @Nonnull HttpInputMessage inputMessage, @Nonnull MethodParameter parameter, @Nonnull Type targetType, @Nonnull Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, @Nonnull HttpInputMessage inputMessage, @Nonnull MethodParameter parameter, @Nonnull Type targetType, @Nonnull Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

}